import Vue from 'vue'
import createLogger from 'vuex/dist/logger'

const debug = true;

// 用户信息的初始数据
const USER_INFO = {
    avatar: false,                         // 头像
    card_id: 0,                         // 名片ID
    company_id: 0,                      // 企业ID（0表示未加入未何企业）
    company_name: 0,                    // 企业名称
    company_info_completion: 0,         // 企业信息完善度
    audit: 0,                           // 企业认证状态
    audit_text: "",                     // 企业认证状态
    department_ids: [],                 // 部门ID
    is_new_user: true,                  // 是否为新注册用户
    mobile: "",                         // 手机号
    nickname: "",                       // 昵称
    open_id: "",                        // 微信openid
    position: "",                       // 职位
    role: 2,                            // 角色ID  0：超管 1：管理员 2：普通员工 3：离职
    role_name: "",                      // 角色名
    status: 0,                          // 会员状态
    tl_id: "",                          // 陀螺ID
    true_name: "",                      // 陀螺ID
    union_id: "",                       // 微信unionid
    user_id: "",                         // 用户ID
    verified_status: 0,                 // 实名认证状态（0：未实名，1：已实名）
};
let StatusBar = 20;
// #ifdef H5
StatusBar = 0;
// #endif
const SYSTEM_INFO = {
    CustomBar: 44 + StatusBar,
    StatusBar: StatusBar,
    Custom: {
        bottom: 58,
        height: 32,
        left: 278,
        right: 365,
        top: 26,
        width: 87,
    },
    windowWidth: 375,
    language: "zh-CN",
    model: "iPhone",
    pixelRatio: 2,
    platform: "ios",
    safeArea: {left: 0, right: 375, top: 0, bottom: 667, width: 375},
    screenHeight: 667,
    screenWidth: 375,
    statusBarHeight: 0,
    system: "iOS 11.0",
    windowBottom: 0,
    windowHeight: 667,
    windowTop: 0
};

function isEmpty(arg) {
    if (arg === undefined) return true;
    else if (arg === null) return true;
    else if (typeof arg === "number" && isNaN(arg)) return true;
    else if (typeof arg === "string" && 0 === arg.length) return true;
    else if (Array.isArray(arg) && 0 === arg.length) return true;
    else if (arg !== null && Object.prototype.toString.call(arg).slice(8, -1).toLowerCase() === 'object' && 0 === Object.keys(arg).length) return true;
    return false
}

function setSystemInfoSync(state, payload, e) {
    const systemInfo = {};
    // #ifndef MP
    systemInfo.StatusBar = e.statusBarHeight;
    if (Vue.$device.isPc || e.windowWidth > 700) {
        systemInfo.CustomBar = e.statusBarHeight + uni.upx2px(100);
    } else if (e.platform === 'android') {
        systemInfo.CustomBar = e.statusBarHeight + 50;
    } else {
        systemInfo.CustomBar = e.statusBarHeight + 45;
    }
    // #endif
    // #ifdef MP-WEIXIN
    systemInfo.StatusBar = e.statusBarHeight;
    const custom = wx.getMenuButtonBoundingClientRect();
    systemInfo.Custom = custom;
    // systemInfo.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
    systemInfo.CustomBar = custom.height + e.statusBarHeight + uni.upx2px(24);
    // #endif
    // #ifdef MP-ALIPAY
    systemInfo.StatusBar = e.statusBarHeight;
    systemInfo.CustomBar = e.statusBarHeight + e.titleBarHeight;
    // #endif
    Vue.$global_util.mapKeys({...e, ...systemInfo}, state.systemInfo, Object.keys(SYSTEM_INFO));
    typeof payload === 'function' && payload(state.systemInfo);
    uni.$emit('setSystemInfoSync', state.systemInfo)
}

export default {
    namespaced: true,
    state: {
        userInfoInfo: {...USER_INFO},
        get userInfo() {
            const $Storage = Vue.$Storage;
            const userInfo = $Storage.getStorageSync('userInfo');
            const u2 = this.userInfoInfo;
            if (!isEmpty(u2) && !isEmpty(u2.user_id)) {
                $Storage.setStorageSync('userInfo', u2, '7d');
            } else if (!isEmpty(userInfo) && !isEmpty(userInfo.user_id)) {
                this.userInfoInfo = userInfo;
            }
            return {...this.userInfoInfo};
        },
        set userInfo(userInfo) {
            this.userInfoInfo = {...userInfo};
            Vue.$Storage.setStorageSync('userInfo', userInfo, '7d');
        },
        systemInfo: {...SYSTEM_INFO},
        tabBar: [
            {
                icon: 'tlIcon-tabbar_card1',
                iconActive: 'tlIcon-tabbar_data2',
                name: '数据',
                path: 'pages/home/index'
            },
            {
                icon: 'tlIcon-tabbar_cardholder1',
                iconActive: 'tlIcon-tabbar_customer2',
                name: '客户',
                path: 'pages/tabBar/client/index'
            },
            {
                icon: 'tlIcon-tabbar_rank1',
                iconActive: 'tlIcon-tabbar_box2',
                name: '百宝箱',
                path: 'pages/tabBar/treasure/index'
            },
            {
                icon: 'tlIcon-tabbar_department1',
                iconActive: 'tlIcon-tabbar_activity1',
                name: '组织',
                path: 'pages/tabBar/branch/index'
            },
            {
                icon: 'tlIcon-tabbar_personalcenter1',
                iconActive: 'tlIcon-tabbar_personalcenter2',
                name: '我的',
                path: 'pages/tabBar/mine/index'
            }
        ],
        isOtherReturnRefresh: false,//隐藏小程序监听判断是否需要刷新数据
    },
    getters: {
        //通过方法访问
        userInfo: state => {
            return state.userInfo
        },
        systemInfo: state => {
            return {
                ...SYSTEM_INFO,
                ...state.systemInfo
            };
        },
        // 1：登录 2：公司 3：名片
        noDataType: state => {
            const userInfo = state.userInfo;
            if (userInfo.company_id === 0 && userInfo.user_id) {
                return 2
            } else if (userInfo.card_id === 0 && userInfo.user_id) {
                return 3
            } else if (userInfo.user_id) {
                return 0
            } else {
                return 1
            }
        }
    },
    mutations: {
        setOtherReturnRefresh(state, payload) {
            if (typeof payload !== "boolean") return;
            if (payload === true) Vue.$global_util.Login.isRefreshUserInfo = true;
            state.isOtherReturnRefresh = payload;
        },
        // 修改用户信息
        modifyUserInfo(state, payload) {
            const jude = Vue.$global_util.jude;
            if (jude.isEmptyObject(payload)) return;
            const userInfo = state.userInfo;
            state.userInfo = {...userInfo, ...payload};
        },
        setUserInfo(state, payload) {
            const jude = Vue.$global_util.jude;
            const userInfo = {
                avatar: ""
            };
            Vue.$global_util.mapKeysData(payload, userInfo, Object.keys(USER_INFO));
            if (typeof userInfo.department_ids === "string") {
                userInfo.department_ids = userInfo.department_ids.split(",")
            }
            state.userInfo = {...USER_INFO, ...userInfo};
        },
        removeUserInfo(state, payload) {
            state.userInfo = {...USER_INFO};
        },
        getUserInfo(state, payload) {
            return {...state.userInfo};
        },
        /**
         * 获取系统信息异步
         * @param state
         * @param payload
         */
        getSystemInfoSync(state, payload) {
            try {
                let result = uni.getSystemInfoSync();
                setSystemInfoSync(state, payload, result)
            } catch (e) {
                uni.getSystemInfo({
                    success(result) {
                        setSystemInfoSync(state, payload, result)
                    }
                })
            }
        }
    },
    actions: {},
    strict: debug, //设置运行模式
    plugin: debug ? [createLogger()] : [] //调试模式加入日志插件
}

